package 代理模式.动态代理.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;

class CglibProxy implements MethodInterceptor {
    private Object target;

    public CglibProxy(Object target) {
        this.target = target;
    }

    public Object getProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("before method " + method.getName());
        Object result = proxy.invokeSuper(obj, args);
        System.out.println("after method " + method.getName());
        return result;
    }
}

class UserServiceImpl {
    public void addUser(String userName) {
        System.out.println("add user: " + userName);
    }
}

public class Main {
    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();
        CglibProxy proxy = new CglibProxy(userService);
        UserServiceImpl userServiceProxy = (UserServiceImpl) proxy.getProxy();
        userServiceProxy.addUser("test");
    }
}